package eiisan.lucenedemo;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @author: eii
 * @time: 2020/8/7 11:59 下午
 */
public class LuceneField {

    /** Field的使用
     * 使用ik分词器 进行索引库创建
     * @throws IOException
     */
    @Test
    public void createIndexWhitIKAnalyzer() throws IOException {
        // 索引库放内存
        // Directory index = new RAMDirectory();
        // 1.索引库放磁盘
        Directory directory = FSDirectory.open(new File("/Users/eii/tmp/index").toPath());
        // 2 基于directory 创建一个IndexWriter   使用ik分词器
        IndexWriterConfig config = new IndexWriterConfig(new IKAnalyzer());
        IndexWriter indexWriter = new IndexWriter(directory, config);
        File dir = new File("/Volumes/mdate/lucene/02.参考资料/searchsource");
        File[] files = dir.listFiles();
        for (File file : files) {
            String fileName = file.getName();
            String filePath = file.getPath();
            String fileContent = FileUtils.readFileToString(file, "utf-8");
            //文件大小
            long fileSize = FileUtils.sizeOf(file);
            //创建field
            Field fieldName = new TextField("name", fileName, Field.Store.YES);

            //fieldPath 不分析，不索引，但要Field存储在文档中
            Field fieldPath = new StoredField("path", filePath);

            Field fieldContent = new TextField("content", fileContent, Field.Store.YES);
            //fieldSizeValue 让数值类型可以进行索引。但是不能存储数据
            Field fieldSizeValue = new LongPoint("size", fileSize);
            //fieldSizeStore 不分析，不索引，但要Field存储在文档中
            Field fieldSizeStore = new StoredField("size", fileSize);
            //创建文档对象
            Document doc = new Document();
            doc.add(fieldName);
            doc.add(fieldPath);
            doc.add(fieldContent);
            doc.add(fieldSizeValue);
            doc.add(fieldSizeStore);
            //把文档对象写入索引库
            indexWriter.addDocument(doc);
        }
        //关闭 indexWriter对象
        indexWriter.close();
    }




}

